package com.yida.common.security.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.yida.common.core.constant.CacheConstants;
import com.yida.common.core.constant.SecurityConstants;
import com.yida.common.core.utils.JwtUtils;
import com.yida.common.core.utils.ServletUtils;
import com.yida.common.core.utils.ip.IpUtils;
import com.yida.common.core.utils.uuid.IdUtils;
import com.yida.system.api.domain.SysUser;
import com.yida.system.api.model.LoginUser;

/**
 * @author ppv
 * @date 2023/03/27
 */
@Component
public class OutsideTokenService {

    @Autowired
    private TokenService tokenService;

    private final static long expireTime = CacheConstants.EXPIRATION;

    /**
     * 创建令牌
     */
    public Map<String, Object> createToken(LoginUser loginUser) {
        String token = IdUtils.fastUUID();
        Long userId = loginUser.getSysOutsideUser().getUserId();
        String userName = loginUser.getSysOutsideUser().getUserName();
        // 20221206
        String areaIds = loginUser.getAreaIds();
        loginUser.setToken(token);
        loginUser.setUserid(userId);
        loginUser.setUsername(userName);
        loginUser.setIpaddr(IpUtils.getIpAddr(ServletUtils.getRequest()));
        // loginUser.getSysUser().setUserId(userId);
        SysUser sysUser = new SysUser();
        sysUser.setUserId(userId);
        loginUser.setSysUser(sysUser);
        tokenService.refreshToken(loginUser);

        // Jwt存储信息
        Map<String, Object> claimsMap = new HashMap<String, Object>();
        claimsMap.put(SecurityConstants.USER_KEY, token);
        claimsMap.put(SecurityConstants.DETAILS_USER_ID, userId);
        claimsMap.put(SecurityConstants.DETAILS_USERNAME, userName);
        claimsMap.put(SecurityConstants.DETAILS_AREA_ID, areaIds);

        // 接口返回信息
        Map<String, Object> rspMap = new HashMap<String, Object>();
        rspMap.put("access_token", JwtUtils.createToken(claimsMap));
        rspMap.put("expires_in", expireTime);
        return rspMap;
    }

}
